﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Data.SqlClient;
using GMS.MainClasses;
using GMS.Dinasty.ReferenceGoods;
using GMS.MainForm;
using GMS.ServiceFunctions.FunctionForControls;
using GMS.ServiceFunctions.Data;
using GMS.Dinasty.DAL;
using GMS.Dinasty.BO;
using GMS.BasicControls;
using GMS.Enums;
using System.Collections;
using GMS.Dinasty.Reporting;
using DevExpress.XtraReports.UI;


namespace GMS.Dinasty.Specifications
{
    public partial class Specifications : ChildForms
    {
        TreeNode SelectedNode = new TreeNode();
        FunctionForTreeView FFTV = new FunctionForTreeView();
        BindingSource mbs = new BindingSource();
        DataSet DS = new DataSet();
        DataTable DT = new DataTable();
        ReturnData RD = new ReturnData();
        BindingSource bsCustomer = new BindingSource();
        
        public String CaptionGood;

        public Specifications()
        {
            InitializeComponent();

            ConnectionString = "server=pavel;uid=pavel;pwd=123456;database=GMSDatabase";

            DTCreate();
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = DT;

            DT.RowChanged += new DataRowChangeEventHandler(DT_RowChanging);

            StoredProcedures = new String[23];
            StoredProcedures[0] = "DInsertSpecificationTemplate";
            StoredProcedures[1] = "DDeleteSpecificationsTemplate";
            StoredProcedures[2] = "DSelectSpecificationsTemplate";
            StoredProcedures[3] = "DSelectSpecificationstemplateContent";
            StoredProcedures[4] = "DInsertSpecificationsTemplates";
            StoredProcedures[5] = "DInsertTemplateSpecificationItem";
            StoredProcedures[6] = "DDeleteSpecificationTemplateWithItems";
            StoredProcedures[7] = "DSelectCustomers";
            StoredProcedures[8] = "DUpdateCustomer";
            StoredProcedures[9] = "DSelectDistributor";
            StoredProcedures[10] = "DInsertCustomer";
            StoredProcedures[11] = "DDeleteCustomer";
            StoredProcedures[12] = "DSelectAllUsers";
            StoredProcedures[13] = "DInsertBill";
            StoredProcedures[14] = "DMakeDeletedSpecification";
            StoredProcedures[15] = "DSelectNumberBillByUser";
            StoredProcedures[16] = "DSelectSpecificationsContent";
            StoredProcedures[17] = "DUpdateSpecificationContent";
            StoredProcedures[18] = "DInsertSpecificationContent";
            StoredProcedures[19] = "DDeleteSpecificationsContent";
            StoredProcedures[20] = "DselectColorPickerrecords";
            StoredProcedures[21] = "DSelectSuffusion_Color";
            StoredProcedures[22] = "DSelectSuffusion";
        }

        void DT_Initialized(object sender, EventArgs e)
        {
            da.Update(DT);
        }

        void DT_RowChanging(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change)
                da.Update(DT);
        }
        private void DTCreate()
        {
            DataColumn dcl = new DataColumn("CaptionGood", Type.GetType("System.String"));

            DT.Columns.Add(dcl);
            dcl = new DataColumn("IdContent");
            dcl.AutoIncrement = true;
            dcl.AutoIncrementSeed = 0;
            dcl.AutoIncrementStep = 1;
            DT.Columns.Add(dcl);
            dcl = new DataColumn("IdBill");
            DT.Columns.Add(dcl);
            dcl = new DataColumn("IdGood");
            DT.Columns.Add(dcl);
            dcl = new DataColumn("UnitCaption", Type.GetType("System.String"));
            DT.Columns.Add(dcl);
            dcl = new DataColumn("Quantity", Type.GetType("System.Double"));
            DT.Columns.Add(dcl);
            dcl = new DataColumn("Price", Type.GetType("System.Double"));
            DT.Columns.Add(dcl);
            dcl = new DataColumn("LowPrice", Type.GetType("System.Double"));
            DT.Columns.Add(dcl);
            dcl = new DataColumn("Summ", Type.GetType("System.Double"));

            dcl.Expression = "Quantity * LowPrice";
            DT.Columns.Add(dcl);
            dcl = new DataColumn("Order");
            DT.Columns.Add(dcl);

            DT.TableNewRow += new DataTableNewRowEventHandler(DT_TableNewRow);
            DT.RowDeleting += new DataRowChangeEventHandler(DT_RowDeleting);
            DT.RowDeleted += new DataRowChangeEventHandler(DT_RowDeleted);
            

        }

        void DT_RowDeleted(object sender, DataRowChangeEventArgs e)
        {
            da.Update(DT);
        }
        void DT_RowDeleting(object sender, DataRowChangeEventArgs e)
        {
            int deletedIndex = int.Parse(e.Row["Order"].ToString());
            foreach (DataRow drw in DT.Select(string.Format("Order > "+deletedIndex.ToString())))
            {
                drw["Order"] = int.Parse(drw["Order"].ToString())-1;
            }
        }

        void DT_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["Order"] = e.Row.Table.Rows.Count + 1;
            da.Update(DT);
            
        }

        private void SelectTemplateSpecification()
        {
            //mbs.DataSource = MRF.ReturnDataSetDB(ConnectionString, StoredProcedures[2]);
            toolStripComboBox1.ComboBox.DataSource = RD.ReturnDataSetDB(ConnectionString, StoredProcedures[2]).Tables[0];
            toolStripComboBox1.ComboBox.DisplayMember = "Captiontemplate";
            toolStripComboBox1.ComboBox.ValueMember = "IdCaption";
        }
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1 && this.dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name.ToString() == "Caption")
            {

                GMS.Dinasty.ReferenceGoods.ReferenceGoods CF = new GMS.Dinasty.ReferenceGoods.ReferenceGoods(this.dataGridView1);
                CF.ConnectionString = ConnectionString;
                CF.ConnectionString="server=pavel;uid=pavel;pwd=123456;database=GMSDatabase";
                
                CF.MdiParent = this.MdiParent;
                CF.Show();
                //dataGridView1.CurrentCell = dataGridView1.CurrentRow.Cells[2];
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            using (SolidBrush brush = new SolidBrush(((DataGridView)sender).RowHeadersDefaultCellStyle.ForeColor))
            {
                if (e.RowIndex + 1 != dataGridView1.Rows.Count)
                {
                    e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), e.InheritedRowStyle.Font, brush, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 3);
                }
            }

        }
        /// <summary>
        /// CH2
        /// формирование блока способствующего перемещению курсора не на поле цена а на поле цена со скидкой
        /// </summary>
        /// <param name="i"></param>
        delegate void SetColumnIndex(int i);
        private void Mymethod(int columnIndex)
        {
            this.dataGridView1.CurrentCell = this.dataGridView1.CurrentRow.Cells["LowPrice"];
        }

        private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
        {

            if (this.dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name.ToString() == "Quantity")
            {
                if (dataGridView1.CurrentCell.ColumnIndex != (dataGridView1.Columns.Count - 1))
                {
                    Int32 nextindex = Math.Min((dataGridView1.Columns.Count - 1), (dataGridView1.CurrentCell.ColumnIndex + 1));
                    SetColumnIndex method = new SetColumnIndex(Mymethod);
                    this.dataGridView1.BeginInvoke(method, nextindex);
                }
            }

        }
        /// окончание CH2
        private void Specifications_Activated(object sender, EventArgs e)
        {
            dataGridView1.Select();
        }
        private void Specifications_Load(object sender, EventArgs e)
        {
            LoadUser();
            SelectTemplateSpecification();
            RefreshTreeView();
            LoadDistributor();
        }
        SqlDataAdapter daTemplates = new SqlDataAdapter();
        private void applytemplateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (toolStripComboBox1.ComboBox.SelectedValue != null)
            {
                SqlConnection connection = new SqlConnection(ConnectionString);
                
                DT.Clear();
                daTemplates.SelectCommand = new SqlCommand(StoredProcedures[3]);
                daTemplates.SelectCommand.CommandType = CommandType.StoredProcedure;
                daTemplates.SelectCommand.Parameters.Add("@IdCaption", SqlDbType.Int).Value = toolStripComboBox1.ComboBox.SelectedValue.ToString();
                daTemplates.SelectCommand.Connection = connection;
                daTemplates.Fill(DT);
            }
            else
                MessageBox.Show("Не выбран шаблон!!!", "Ошибка выбора", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void toolStripTextBox1_KeyUp(object sender, KeyEventArgs e)
        {
            /// <summary>
            /// CH3
            /// формирование скики а так же провреки связанные со скидкой, проверка на допустимые значения
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            if (toolStripTextBox1.Text.Length>0 && Char.IsDigit(toolStripTextBox1.Text, toolStripTextBox1.Text.Length - 1))
            {
                if (dataGridView1.SelectedRows != null)
                {
                    foreach (DataGridViewRow DGWR in dataGridView1.SelectedRows)
                    {
                        if (DGWR.Cells["Price"].Value == null || DGWR.Cells["Price"].Value.ToString().Length == 0)
                            DGWR.Cells["LowPrice"].Value = 0;
                        else
                            DGWR.Cells["LowPrice"].Value = Convert.ToDecimal(DGWR.Cells["Price"].Value.ToString().Replace('.', ',')) - Convert.ToDecimal(DGWR.Cells["Price"].Value.ToString().Replace('.', ',')) / 100 * Convert.ToDecimal(toolStripTextBox1.Text);
                    }
                }
            }
            ///окончание CH3
        }

        private void insertrowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow.Index != dataGridView1.Rows.Count-1)
            {
                UpdateRowOldIdContent(DT, dataGridView1.CurrentRow.Index + 1);
                DataRow dr = DT.NewRow();
                dr["Order"] = dataGridView1.CurrentRow.Index + 2;
                DT.Rows.InsertAt(dr, dataGridView1.CurrentRow.Index + 1);
            }
        }

        private void AddToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DT.Rows.Count != 0)
            {
                DataTable Dt = DT.Clone();
                
                Dt = RD.ReturnDataSetDB(ConnectionString, StoredProcedures[3] + " " + toolStripComboBox1.ComboBox.SelectedValue.ToString()).Tables[0]. Copy();
                DataRow dr;
                Int32 g = dataGridView1.RowCount;
                Int32 f = dataGridView1.CurrentRow.Index;
                if (g == f+1)
                    f = f - 1;
                for (Int32 j = 0; j < Dt.Rows.Count; j++)
                {
                    //dr = Dt.Rows[j];
                    UpdateRowOldIdContent(DT, f + j + 1);
                    dr = DT.NewRow();
                    dr["IdGood"] = Dt.Rows[j]["IdGood"];
                    dr["CaptionGood"] = Dt.Rows[j]["CaptionGood"];
                    dr["UnitCaption"] = Dt.Rows[j]["UnitCaption"];
                    dr["Quantity"] = Dt.Rows[j]["Quantity"];
                    dr["Price"] = Dt.Rows[j]["Price"];
                    dr["LowPrice"] = Dt.Rows[j]["LowPrice"];
                    dr["Order"] = (f + j + 2).ToString();
                    DT.Rows.InsertAt(dr, f + j + 1);
                }

            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SqlConnection SC = new SqlConnection(ConnectionString);
            SC.Open();

            Int32 i;
            i =Convert.ToInt32(RD.ReturnDataSetDB(ConnectionString, StoredProcedures[4] + " " + toolStripComboBox1.Text.Trim()).Tables[0].Rows[0][0].ToString());

            SqlTransaction ST = SC.BeginTransaction();
            try
            {
                foreach (DataRow DR in DT.Rows)
                {
                    SqlCommand SCC = new SqlCommand(StoredProcedures[5] + " " + i.ToString() + ", " + DR[0].ToString(), SC);
                    SCC.Transaction = ST;
                    SCC.ExecuteNonQuery();
                    ST.Commit();
                }
            }
            catch (SqlException SQLE)
            {
                ST.Rollback();
                MessageBox.Show(SQLE.Message.ToString(), "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                SC.Close();
            }
            
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Удаление шаблона и всего его содержимого. Вы уверены?", "Предупреждение!!!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SqlConnection SC = new SqlConnection(ConnectionString);
                SC.Open();
                SqlTransaction ST = SC.BeginTransaction();
                try
                {
                    SqlCommand SCC = new SqlCommand(StoredProcedures[6] + " " + toolStripComboBox1.ComboBox.SelectedValue.ToString(), SC);
                    SCC.Transaction = ST;
                    SCC.ExecuteNonQuery();
                    ST.Commit();
                }
                //catch(SqlException SQLE)
                catch
                {
                    ST.Rollback();
                    //MessageBox.Show(SQLE.Message.ToString(), "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                SC.Close();
                SelectTemplateSpecification();
            }
        }
        private void RefreshTreeView()
        {
            DAL.DataAccessCustomer DAC = new DAL.DataAccessCustomer();
            myTreeview1.ListDatasourse = DAC.Persons(DAC.SelectCustomer(ConnectionString, StoredProcedures[7]));
        }

        private void LoadDistributor()
        {
            DataSet DS = RD.ReturnDataSetDB(ConnectionString, StoredProcedures[9]+" null");
            comboBox1.DataSource = DS.Tables[0];
            comboBox1.DisplayMember = "Caption";
            comboBox1.ValueMember = "Id";
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == false)
                comboBox1.Enabled = false;
            else
                comboBox1.Enabled = true;
        }

        private void checkBox1_MouseEnter(object sender, EventArgs e)
        {
            toolTipDistributorHelp.Active = false;
            toolTipDistributorHelp.Active = true;
        }

        private void contextMenuStripCustomers_Opening(object sender, CancelEventArgs e)
        {
            if (myTreeview1.SelectedNode == null)
                e.Cancel = true;
        }
        #region удаление, добавление, редактирование заказчиков

        private void AddCustomer_Click(object sender, EventArgs e)
        {
            InsertCustomer IU = new InsertCustomer(EditMode.AddIn);
            Point P = new Point(12, 50);
            IU.Location = P;
            myTreeview1.Controls.Add(IU);
        }


        private void addSubCustomer_Click(object sender, EventArgs e)
        {
            
            InsertCustomer IU = new InsertCustomer(EditMode.AddIn);
            IU.IdParentUser = Convert.ToInt32(myTreeview1.SelectedNode.Tag);
            Point P = new Point(12, myTreeview1.SelectedNode.Bounds.Y + myTreeview1.SelectedNode.Bounds.Height);
            IU.Location = P;
            myTreeview1.Controls.Add(IU);
        }

        private void editCustomer_Click(object sender, EventArgs e)
        {
            InsertCustomer IU = new InsertCustomer(EditMode.Editing);
            IU.DataNode = myTreeview1.SelectedNode;

            if (myTreeview1.SelectedNode.Parent == null)
                IU.IdParentUser = 0;
            else
                IU.IdParentUser = Convert.ToInt32(myTreeview1.SelectedNode.Parent.Tag);
            Point P = new Point(12, myTreeview1.SelectedNode.Bounds.Y + myTreeview1.SelectedNode.Bounds.Height);
            IU.Location = P;
            myTreeview1.Controls.Add(IU);
        }

        private void deleteCustomer_Click(object sender, EventArgs e)
        {
            InsertCustomer IU = new InsertCustomer(EditMode.Deleting);
            IU.DataNode = myTreeview1.SelectedNode;
            Point P = new Point(12, myTreeview1.SelectedNode.Bounds.Y + myTreeview1.SelectedNode.Bounds.Height);
            IU.Location = P;
            myTreeview1.Controls.Add(IU);

        }
#endregion
        #region добавление, удаление номеров спецификаций
        private void GetUser()
        {
            DataAccesUser DAU = new DataAccesUser();
            
        }
        private CustomerSpecifications CS;
        private void customerSpecifications_Click(object sender, EventArgs e)
        {
            CS = new CustomerSpecifications();
            DataAccessSpecifications DAS = new DataAccessSpecifications();
            CS.IdCustomer = Convert.ToInt32(myTreeview1.SelectedNode.Tag.ToString());
            CS.IdDistributor = Convert.ToInt32(comboBox1.SelectedValue.ToString());
            CS.Officers = (chooseUser.Tag as List<User>);
            CS.DateStart = DateTime.Now.AddMonths(-1);
            CS.DateEnd = DateTime.Now.AddDays(1);
            CS.DeletedSpecifications = 1;
            CS.Specifications = SpecificationsLoad(CS.IdDistributor, CS.IdCustomer, CS.Officers, CS.DateStart, CS.DateEnd, CS.DeletedSpecifications);
            CS.SpecificationsLoad();
            Point Location = new Point(12, myTreeview1.SelectedNode.Bounds.Bottom);
            CS.Location = Location;
            CS.tabControl1.Click +=new EventHandler(tabControl1_Click);
            CS.listBox1.SelectedValueChanged += new EventHandler(listBox1_SelectedValueChanged);
            myTreeview1.Controls.Add(CS);
        }
        SqlDataAdapter da = new SqlDataAdapter();
        
        private void listBox1_SelectedValueChanged(object sender, EventArgs e )
        {
            if (sender is ListBox && (sender as ListBox).SelectedItem != null)
            {
                DT.Clear();
                LoadSpecificationContent(((sender as ListBox).SelectedItem as Specification).IdSpecifications);
                dataGridView1.DataSource = DT;

                specificationNumber = ((sender as ListBox).SelectedItem as Specification).IdSpecifications.ToString();
                dateSpecification = ((sender as ListBox).SelectedItem as Specification).DateDischarge.ToShortDateString();
            }
        }
        private void tabControl1_Click(object sender, EventArgs e)
        {
            CS.Specifications = SpecificationsLoad(CS.IdDistributor, CS.IdCustomer, CS.Officers, CS.DateStart, CS.DateEnd, CS.DeletedSpecifications);
            CS.SpecificationsLoad();
        }
        private List<Specification> SpecificationsLoad(int Distributor, int Customer, List<User> Officers, DateTime DateStart, DateTime DateEnd, int DeletedSpecification)
        {
            DataAccessSpecifications DAS = new DataAccessSpecifications();
            List<Specification> specifications = DAS.SelectSpecificationsBydistributorCustomerOfficer(ConnectionString, StoredProcedures[15] , Distributor, Customer, Officers, DateStart, DateEnd, DeletedSpecification);
            return specifications;
        }
        #endregion
        #region операции с выбором пользователей
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UsersList UL = new UsersList();
            Point location = new Point(chooseUser.Bounds.X, chooseUser.Bounds.Bottom);
            UL.Location = location;
            DataAccesUser DAU = new DataAccesUser();

            UL.AllUsers = DAU.SelectUsers(ConnectionString, StoredProcedures[12]);

            UL.CurUsers = (chooseUser.Tag as List<User>);
            chooseUser.Parent.Controls.Add(UL);
            UL.BringToFront();
        }
        private void LoadUser()
        {
            DataAccesUser DAU = new DataAccesUser();
            chooseUser.Text = DAU.CreateUser(DAU.Test()).UserShortName();
            List<User> user = new List<User>();
            user.Add(DAU.CreateUser(DAU.Test()));
            chooseUser.Tag = user;
            
        }
        private void splitContainer1_Panel1_ControlRemoved(object sender, ControlEventArgs e)
        {
            if ((e.Control is UsersList))
            {
                chooseUser.Tag = (e.Control as UsersList).CurUsers;
                contactor = string.Empty;
                if ((e.Control as UsersList).CurUsers.Count == 1)
                    chooseUser.Text = (e.Control as UsersList).CurUsers[0].UserShortName();
                else
                    chooseUser.Text = "...";
            }
        }
        private void chooseUser_TextChanged(object sender, EventArgs e)
        {
            Control[] controls = myTreeview1.Controls.Find("CustomerSpecifications", false);
            if (controls.Length > 0)
            {
                CustomerSpecifications CS = (controls[0] as CustomerSpecifications);
                CS.Specifications = SpecificationsLoad(CS.IdDistributor, CS.IdCustomer, CS.Officers, CS.DateStart, CS.DateEnd, CS.DeletedSpecifications);
                CS.SpecificationsLoad();
            }
        }
        #endregion
        #region операции с номенклатурой спецификаций
        private void LoadSpecificationContent(int IdSpecification)
        {
            SqlConnection connection = new SqlConnection();
            connection.ConnectionString = ConnectionString;

            da.SelectCommand = new SqlCommand(StoredProcedures[16]);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@IdBill", SqlDbType.Int).Value = IdSpecification;
            da.SelectCommand.Connection = connection;
            da.Fill(DT);
            //
            da.InsertCommand = new SqlCommand(StoredProcedures[18]);
            da.InsertCommand.CommandType = CommandType.StoredProcedure;

            SqlParameter insertParameter = null;
            insertParameter = da.InsertCommand.Parameters.Add("@IdContent", SqlDbType.Int);
            insertParameter.SourceColumn = "IdContent";
            insertParameter.SourceVersion = DataRowVersion.Current;

            insertParameter = da.InsertCommand.Parameters.Add("@IdBill", SqlDbType.Int);
            insertParameter.Value = (CS.listBox1.SelectedItem as Specification).IdSpecifications;

            insertParameter = da.InsertCommand.Parameters.Add("@IdGood", SqlDbType.Int);
            insertParameter.SourceColumn = "IdGood";
            insertParameter.SourceVersion = DataRowVersion.Current;


            insertParameter = da.InsertCommand.Parameters.Add("@CaptionGood", SqlDbType.Text);
            insertParameter.SourceColumn = "CaptionGood";
            insertParameter.SourceVersion = DataRowVersion.Current;

            insertParameter = da.InsertCommand.Parameters.Add("@IdUnit", SqlDbType.Text);
            insertParameter.SourceColumn = "UnitCaption";
            insertParameter.SourceVersion = DataRowVersion.Current;

            insertParameter = da.InsertCommand.Parameters.Add("@Quantity", SqlDbType.Decimal);
            insertParameter.SourceColumn = "Quantity";
            insertParameter.SourceVersion = DataRowVersion.Current;

            insertParameter = da.InsertCommand.Parameters.Add("@Price", SqlDbType.Decimal);
            insertParameter.SourceColumn = "Price";
            insertParameter.SourceVersion = DataRowVersion.Current;

            insertParameter = da.InsertCommand.Parameters.Add("@LowPrice", SqlDbType.Decimal);
            insertParameter.SourceColumn = "LowPrice";
            insertParameter.SourceVersion = DataRowVersion.Current;

            insertParameter = da.InsertCommand.Parameters.Add("@Order", SqlDbType.Int);
            insertParameter.SourceColumn = "Order";
            insertParameter.SourceVersion = DataRowVersion.Current;

            
            //
            da.UpdateCommand = new SqlCommand(StoredProcedures[17]);
            da.UpdateCommand.CommandType = CommandType.StoredProcedure;

            SqlParameter updateParameter = null;
            updateParameter = da.UpdateCommand.Parameters.Add("@IdBill", SqlDbType.Int);
            updateParameter.Value = (CS.listBox1.SelectedItem as Specification).IdSpecifications;

            updateParameter = da.UpdateCommand.Parameters.Add("@IdContent", SqlDbType.Int);
            updateParameter.SourceColumn = "IdContent";
            updateParameter.SourceVersion = DataRowVersion.Current;

            updateParameter = da.UpdateCommand.Parameters.Add("@IdGood", SqlDbType.Int);
            updateParameter.SourceColumn = "IdGood";
            updateParameter.SourceVersion = DataRowVersion.Current;

            updateParameter = da.UpdateCommand.Parameters.Add("@CaptionGood", SqlDbType.Text);
            updateParameter.SourceColumn = "CaptionGood";
            updateParameter.SourceVersion = DataRowVersion.Current;

            updateParameter = da.UpdateCommand.Parameters.Add("@IdUnit", SqlDbType.Text);
            updateParameter.SourceColumn = "UnitCaption";
            updateParameter.SourceVersion = DataRowVersion.Current;

            updateParameter = da.UpdateCommand.Parameters.Add("@Quantity", SqlDbType.Float);
            updateParameter.SourceColumn = "Quantity";
            updateParameter.SourceVersion = DataRowVersion.Current;

            updateParameter = da.UpdateCommand.Parameters.Add("@Price", SqlDbType.Float);
            updateParameter.SourceColumn = "Price";
            updateParameter.SourceVersion = DataRowVersion.Current;

            updateParameter = da.UpdateCommand.Parameters.Add("@LowPrice", SqlDbType.Float);
            updateParameter.SourceColumn = "LowPrice";
            updateParameter.SourceVersion = DataRowVersion.Current;

            updateParameter = da.UpdateCommand.Parameters.Add("@Order", SqlDbType.Float);
            updateParameter.SourceColumn = "Order";
            updateParameter.SourceVersion = DataRowVersion.Current;
            //
            da.DeleteCommand = new SqlCommand(StoredProcedures[19]);
            da.DeleteCommand.CommandType = CommandType.StoredProcedure;

            SqlParameter deleteParameter = null;

            deleteParameter = da.DeleteCommand.Parameters.Add("@IdBill", SqlDbType.Int);
            deleteParameter.Value = (CS.listBox1.SelectedItem as Specification).IdSpecifications;

            deleteParameter = da.DeleteCommand.Parameters.Add("@IdContent", SqlDbType.Int);
            deleteParameter.SourceColumn = "IdContent";
            deleteParameter.SourceVersion = DataRowVersion.Current;
            //
            da.InsertCommand.Connection = connection;
            da.UpdateCommand.Connection = connection;
            da.DeleteCommand.Connection = connection;
            connection.Close();
        }


        #endregion
        private CalculateDimensionsA constructor;
        private ConstructorStrips constructorStrips;
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >=0 && dataGridView1.Columns[e.ColumnIndex].Name == "Caption" && dataGridView1.Cursor == Cursors.Hand)
            {
                object o = new Good(dataGridView1.CurrentCell.Value.ToString());
                if (o is Good)
                {
                    if ((o as Good).GroupGood == 1)
                    {
                        constructor = new CalculateDimensionsA();
                        constructor.Dims = (o as Good).Dims;
                        Point location = this.PointToClient(Control.MousePosition);
                        location.X = location.X - dataGridView1.Columns["Caption"].Width;
                        location.Y = location.Y + 10;
                        constructor.Location = location;
                        this.Controls.Add(constructor);
                    }
                    else
                    {
                        constructorStrips = new ConstructorStrips(dataGridView1);
                        constructorStrips.Scans = (o as Good).Scans;
                        Point location = this.PointToClient(Control.MousePosition);
                        location.X = location.X - dataGridView1.Columns["Caption"].Width;
                        location.Y = location.Y + 10;
                        constructorStrips.Location = location;
                        this.Controls.Add(constructorStrips);
                    }
                }
            }
            //textBox1.Text = DT.Rows[dataGridView1.CurrentRow.Index].RowState.ToString();
        }
        private void Specifications_ControlRemoved(object sender, ControlEventArgs e)
        {
            if (constructor != null)
            {
                Good tempVal = new Good(dataGridView1.CurrentCell.Value.ToString());
                tempVal.Dims.Clear();
                tempVal.Dims = constructor.Dims;
                dataGridView1.CurrentCell.Value = tempVal.InputString();
                dataGridView1.ReadOnly = false;

            }
        }
        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress);
        }

        void Control_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name == "Quantity" 
                || dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name == "LowPrice")
            {
                if (e.KeyChar == 46)
                    e.KeyChar = ',';
            }
        }
        void UpdateRowOldIdContent(DataTable dataTable, int IndexRow)
        {
            foreach (DataRow drw in dataTable.Select(string.Format("Order > " + IndexRow.ToString())))
            {
                drw["Order"] = int.Parse(drw["Order"].ToString()) + 1;
            }
        }

        private void colorPickerToolStripButton_Click(object sender, EventArgs e)
        {
            ShowColorPicker();
        }
        private void ShowColorPicker()
        {
            ColorPicker cp = new ColorPicker();
            cp.ConnectionString = ConnectionString;
            cp.SelectColorCommand = StoredProcedures[20];
            cp.SelectSuffusion_ColorCommand = StoredProcedures[21];
            cp.SelectSuffusionCommand = StoredProcedures[22];
            Point sceenLocation = toolStrip1.Parent.PointToScreen(new Point(toolStrip1.Bounds.Left, toolStrip1.Bounds.Bottom));
            cp.Location = this.PointToClient(sceenLocation);
            this.Controls.Add(cp);
            cp.BringToFront();
            cp.applyLinkLabel1.Click += new EventHandler(applyLinkLabel1_Click);

        }

        void applyLinkLabel1_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dr in dataGridView1.SelectedRows)
            {
                //object o = (dr.Cells["Caption"].Value as Good);
                Good good = new Good(dr.Cells["Caption"].Value.ToString());
                good.Suffusion = ((sender as LinkLabel).Parent as ColorPicker).NewSuffusion;
                good.Color = ((sender as LinkLabel).Parent as ColorPicker).NewColor;
//                Good good = new Good(dr.Cells["Caption"].Value.ToString());
//                good.Suffusion = ((sender as LinkLabel).Parent as ColorPicker).NewSuffusion;
//                good.Color = ((sender as LinkLabel).Parent as ColorPicker).NewColor;
                dr.Cells["Caption"].Value = good.InputString();
            }

        }
        string distributor = string.Empty;
        string customer = string.Empty;
        string specificationNumber = string.Empty;
        string dateSpecification = string.Empty;
        string contactor = string.Empty;
        DataTable dt; 
        private void simpleSpecificationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            specificationsNoDiscountReport rep = new specificationsNoDiscountReport(distributor, customer, specificationNumber, dateSpecification, dt);
            rep.ShowPreview();
        }
        private void FillReportDt()
        {
            dt = new DataTable();
            DataColumn dc = new DataColumn("order");
            dt.Columns.Add(dc);

            dc = new DataColumn("caption");
            dt.Columns.Add(dc);

            dc = new DataColumn("units");
            dt.Columns.Add(dc);

            dc = new DataColumn("quantity");
            dt.Columns.Add(dc);

            dc = new DataColumn("price");
            dt.Columns.Add(dc);

            dc = new DataColumn("lowprice");
            dt.Columns.Add(dc);

            dc = new DataColumn("summ");
            dt.Columns.Add(dc);

            dc = new DataColumn("idgood");
            dt.Columns.Add(dc);

            dc = new DataColumn("orderDisplay");
            dc.AutoIncrement = true;
            dc.AutoIncrementSeed = 1;
            dc.AutoIncrementStep = 1;
            dt.Columns.Add(dc);

            List<DataGridViewRow> rows = new List<DataGridViewRow>();

            foreach (DataGridViewRow dgwr in dataGridView1.SelectedRows)
            {
                rows.Add(dgwr);
            }
            rows.Sort(CompareContentSoecification);
            foreach(DataGridViewRow dgwr in rows)
            {
                DataRow dr = dt.NewRow();
                dr["order"] = (dgwr.Index + 1).ToString();
                dr["caption"] = dgwr.Cells["Caption"].Value.ToString();
                dr["units"] = dgwr.Cells["metages"].Value.ToString();
                dr["quantity"] = dgwr.Cells["quantity"].Value.ToString();
                dr["price"] = dgwr.Cells["price"].Value.ToString();
                dr["lowprice"] = dgwr.Cells["lowprice"].Value.ToString();
                dr["summ"] = dgwr.Cells["summ"].Value.ToString();
                dr["idgood"] = dgwr.Cells["idcaption"].Value.ToString();
                dt.Rows.Add(dr);
            }


        }

        private static int CompareContentSoecification(DataGridViewRow x, DataGridViewRow y)
        {
            if (x == null)
            {
                if (y == null)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                if (y == null)
                {
                    return 1;
                }
                else
                {
                    int retval = (x.Index+1).CompareTo(y.Index+1);

                    if (retval != 0)
                    {
                        return retval;
                    }
                    else
                    {
                        return (x.Index + 1).CompareTo(y.Index + 1);
                    }
                }
            }
        }
        
        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            distributor = comboBox1.Text;
        }

        private void myTreeview1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            customer = myTreeview1.SelectedNode.Text + " " + myTreeview1.SelectedNode.ToolTipText;
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            FillReportDt();
        }

        private void percentSpecificationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            specificationsDisplayDiscountReport rep = new specificationsDisplayDiscountReport(distributor, customer, specificationNumber, dateSpecification, dt);
            rep.ShowPreview();
        }

        private void specificationTwoPriceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            specificationsReport rep = new specificationsReport(distributor, customer, specificationNumber, dateSpecification, dt);
            rep.ShowPreview();
        }

        private void makeBillToolStripMenuItem_Click(object sender, EventArgs e)
        {
            billNoVatReport rep = new billNoVatReport(distributor, customer, dt, specificationNumber, dateSpecification);
            rep.ShowPreview();
        }

        private void makeSalesInvoiceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            salesInvoiceNoVatReport rep = new salesInvoiceNoVatReport(distributor, customer, specificationNumber, 1.ToString(), dateSpecification, dt);
            rep.ShowPreview();
        }

        private void makeOrderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (chooseUser.Text != "...")
            {
                ChooseDistributor cd = new ChooseDistributor(ConnectionString);
                Point Location = toolStrip1.Parent.PointToScreen(new Point(toolStrip1.Bounds.Left, toolStrip1.Bounds.Bottom));
                cd.Location = this.PointToClient(Location);
                this.Controls.Add(cd);
                cd.BringToFront();
                cd.Data = dt;
                cd.SpecificationNumber = specificationNumber;
                /*
                contactor = cd.Contractor;
                orderReport rep = new orderReport(specificationNumber, contactor, dt);
                rep.ShowPreview();*/
            }
        }

        private void StripToolStripButton_Click(object sender, EventArgs e)
        {
            QuantityStrips qs = new QuantityStrips();
            qs.SourceTable = DT;
            Point Location = toolStrip1.Parent.PointToScreen(new Point(toolStrip1.Bounds.Left, toolStrip1.Bounds.Bottom));
            qs.Location = this.PointToClient(Location);
            this.Controls.Add(qs);
            qs.BringToFront();
        }
    }
}
